import { Order } from '@libs/db/models/order.model';
import { Injectable } from '@nestjs/common';
import { ReturnModelType } from '@typegoose/typegoose';
import { InjectModel } from 'nestjs-typegoose';

@Injectable()
export class OrdersService {
  constructor(
    @InjectModel(Order)
    private readonly orderModel: ReturnModelType<typeof Order>,
  ) {}

  create(order: Order) {
    return this.orderModel.create(order);
  }

  async findAll(query: any) {
    let { size, currentPage, status = null } = query || {};
    let where: any = { status: { $ne: 0 } };
    if (status) {
      where.status.$eq = status;
    }
    size = Number(size);
    currentPage = Number(currentPage);
    const res = await this.orderModel
      .find(where)
      .populate('user')
      .skip((currentPage - 1) * size)
      .limit(size)
      .sort({ _id: -1 });
    const total = await this.orderModel.countDocuments(where);
    return {
      items: res,
      total,
    };
  }

  findOne(id: string) {
    return this.orderModel.findOne({ _id: id }).populate('user');
  }

  update(id: string, order: Order) {
    return this.orderModel.updateOne({ _id: id }, order);
  }

  remove(id: string) {
    return this.orderModel.deleteOne({ _id: id });
  }
}
